package com.example.retrofit;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;

import com.example.retrofit.api.ApiService;

import java.io.IOException;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class MainActivity extends AppCompatActivity {

    Retrofit retrofit;
    OkHttpClient okHttpClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //创建日志拦截器
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.d("guaimiao", message);
            }
        }).setLevel(HttpLoggingInterceptor.Level.BODY);

        //创建okHttpClient对象 添加日志拦截
        okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .build();

        //创建retrofit对象 添加请求的网址 日志拦截
        retrofit = new Retrofit.Builder()
                .baseUrl("https://api.github.com/")
                .client(okHttpClient)
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();

        //通过retrofit对象 创建api对象 然后操作接口里面的方法
        ApiService apiService = retrofit.create(ApiService.class);

        //同步请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Response<String> response = apiService.getTest("这是一个网络请求").execute();
                    Log.d("guaimiao", response.body());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        //异步请求
        apiService.getTest("这是一个网络请求").enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Log.d("guaimiao", response.body());
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });
    }
}